import { Collection, DatasetListItem, MAX_NAME_LENGTH } from '@/common';
import datasetService from '@/api/services/datasetService';
import { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Descriptions,
  Dropdown,
  Input,
  MenuProps,
  message,
  Modal,
  Space,
  Spin,
  Splitter,
  Table,
  Tag,
  Typography,
} from 'antd';
import {
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  EllipsisOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { SvgIcon } from '@/components/icon';
import dayjs from 'dayjs';
import { useUpdateEffect } from 'react-use';
import { useDebounceFn } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
// import EmptyPape from '@/components/empty/EmptyPage';
import EmptyPape from '@/components/NotData';
import { Size } from '@/types/common';
import { useContextSelector } from 'use-context-selector';
import { ApiManageContext } from '../context';
import { ApiDatasetEvent, ApiItem } from '@/types/api';
import React from 'react';
import ApiEditModal from '@/pages/api-manage/components/ApiEditModal';
import { ItemType } from 'antd/es/menu/interface';
import { debounce } from 'lodash';
import { useDatasetStore } from '@/store/datasetStore';
import { useRouter, useParams } from '@/router/hooks';
import Modals from '@/components/modals/Modals';
import { formatData } from '@/utils/time';
import { validateAndConvertValue } from './NewApiModal';
import Tables from '@/components/tables/tables';
import EmptyTip from '@/components/EmptyTip';
const { Text } = Typography;

interface Props {
  selectedItem: DatasetListItem | undefined;
  isAdmin: boolean;
  isPermit: boolean;
  parentSize: Size;
}
const ApiTable = ({ selectedItem, isAdmin, isPermit, parentSize }: Props) => {
  const [collections, setCollections] = useState<Collection[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchValue, setSearchValue] = useState('');
  const [loading, setLoading] = useState(true);
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Collection[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [newName, setNewName] = useState('');
  const [method, setMethod] = useState('get'); // 方法类型状态
  const [path, setPath] = useState('');
  const { appId = '' } = useParams() as { appId: string };
  const [isBatchDelete, setIsBatchDelete] = useState(false);
  const [editItem, setEditItem] = useState<Collection | undefined>(undefined);
  const { isPc } = useWindowWidth();
  const [expandedData, setExpandedData] = useState<{ [key: string]: ApiItem }>({});
  const [expandLoading, setExpandLoading] = useState<{ [key: string]: boolean }>({});
  const { event$ } = useContextSelector(ApiManageContext, (s) => s);

  const [apiEditModalVisible, setApiEditModalVisible] = useState(false);
  const [onItem, setOnItem] = useState<ItemType>({});
  const [funcProp, setFuncProp] = useState<ItemType>({});
  const [recordId, setRecordId] = useState<ItemType>();
  const { loadAllDatasets1 } = useDatasetStore();
  const fetchExpandedData = async (record: Collection) => {
    console.log('record=============', record);
    setExpandLoading((prev) => ({ ...prev, [record.collectionId]: true }));
    // Simulate an API call
    // const data = await datasetService.datasetDataV2List({
    //   collectionId: record._id,
    //   searchText: '',
    //   offset: 0,
    //   pageSize: 15,
    // });
    const data = await datasetService.apiDataV2List(record.collectionId);
    // console.log('data1=============', data1);
    console.log('data=============', data);
    // const apiItem = JSON.parse(data.list[0].q) as ApiItem;
    const apiItem = JSON.parse(data?.metadata?.function) as ApiItem;
    console.log('apiItem=============', apiItem);
    setExpandedData((prev) => ({ ...prev, [record._id]: apiItem }));
    setExpandLoading((prev) => ({ ...prev, [record._id]: false }));

    const apiItemnew = transform(apiItem.function);
    // const apiItemnew = apiItem.function.parameters;
    if (apiItemnew) {
      apiItemnew.fullName = apiItem.http_url;
    }
    console.log('apiItemnew=============', apiItem, apiItemnew);

    // setRecordId(data?.list?.[0]._id);
    setRecordId(data?._id);
    // setRecordId(record._id);
    setFuncProp(apiItem);
    setOnItem(apiItemnew);
  };

  const submit = useCallback(
    debounce(async (values) => {
      try {
        const newproperties = generateKeyValueObject(values.properties.list);

        const newrequired = values.properties.list.flatMap((item) =>
          item.fourth === '是' ? [item.first] : [],
        );

        const newProp = {
          ...funcProp,
          function: {
            ...funcProp.function,
            description: values.description,
            parameters: {
              ...funcProp.function.parameters,
              properties: newproperties,
              required: newrequired,
            },
          },
        };

        // await datasetService.updateCollectionApi({
        //   data_id: recordId,
        //   functionSchema: newProp,
        // });

        await datasetService.updateDatesetData({
          id: editItem?.collectionId,
          name: editItem?.fileName,
          datasetId: editItem?.datasetId,
          functionSchema: newProp,
        });

        message.success('修改成功');
        setExpandedData((prev) => ({
          ...prev,
          [editItem._id]: newProp,
        }));
        run();
        setApiEditModalVisible(false);
        setRecordId('');
        fetchExpandedData(editItem);
      } catch (error) {
        // message.error('提交失败');
        console.error('API Error:', error);
      }
    }, 300), // 500毫秒防抖间隔
    [funcProp, recordId], // 依赖项
  );

  const generateKeyValueObject = (
    list: {
      first: string; // 参数名称
      second: string; // 参数说明
      third: string; // 参数类型
      fourth: string; // 是否必填
      fifth: string[]; // 示例值
      enum: string[]; // 示例值
    }[],
  ): Record<string, { type: string; description: string; enum?: any[]; required: boolean }> => {
    return list.reduce((acc, item) => {
      // 过滤空值
      // if (!item.first || !item.second || !item.third) return acc;

      // 构造参数对象
      const paramObject: {
        type: string;
        description: string;
        enum?: any[];
        required: boolean;
      } = {
        type: item.third || 'string',
        description: item.second,
        required: item.fourth === '是' ? true : false,
      };

      // 只有当enum不为空列表时才添加enum字段
      if (item.enum && item.enum.length > 0) {
        paramObject.enum = [
          ...new Set(
            item.enum.map((value) => {
              const { convertedValue } = validateAndConvertValue(item.third, String(value));
              return convertedValue;
            }),
          ),
        ];
      }

      acc[item.first] = paramObject;
      return acc;
    }, {} as Record<string, { type: string; description: string; enum?: any[]; required: boolean }>);
  };

  const transform = (data: any) => {
    const userinfoEntries = convertObjectToKeyValueArray(
      data.parameters.properties || {},
      data.parameters.required,
    );

    const newData = {
      ...data,
      properties: {
        list: userinfoEntries,
      },
    };
    return newData;
  };

  function convertObjectToKeyValueArray<T>(
    obj: Record<string, T>,
    required: string[],
  ): KeyValuePair<T>[] {
    return Object.entries(obj || {}).map(([key, value]) => ({
      first: key,
      second: value.description,
      third: value.type,
      fourth: required.includes(key) ? '是' : '否',
      fifth: value?.enum || [],
    }));
  }

  const parameterList = (apiItem: ApiItem) => {
    console.log('apiItem========11111=====', apiItem);
    if (!apiItem?.function?.parameters) {
      return;
    }
    const properties = apiItem.function.parameters.properties;
    const required = apiItem.function.parameters.required;
    return (
      <Descriptions
        size="small"
        layout="vertical"
        contentStyle={{ fontSize: '12px', color: '#a3a3a3' }}
        labelStyle={{ fontSize: '12px' }}
        column={5}
      >
        {Object.keys(properties).map((key, index) => (
          <React.Fragment key={`${key}_${index}`}>
            <Descriptions.Item
              label={index === 0 ? '参数名称' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {key}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '参数类型' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {properties[key].type}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '参数说明' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {properties[key].description}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '必须' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {required.includes(key) ? '是' : '否'}
            </Descriptions.Item>
            <Descriptions.Item
              label={index === 0 ? '示例值' : ''}
              labelStyle={index !== 0 ? { display: 'none' } : {}}
            >
              {properties?.[key]?.enum?.join(', ')}
            </Descriptions.Item>
          </React.Fragment>
        ))}
      </Descriptions>
    );
  };

  const getHttpMethodColor = (method: string) => {
    switch (method) {
      case 'get':
        return '#61affe';
      case 'post':
        return '#49cc90';
      case 'put':
        return '#F9D93E';
      case 'delete':
        return '#f93e3e';
      default:
        return '#61affe';
    }
  };

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Collection[]) => {
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };

  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: '数据接口名称',
      dataIndex: 'fileName',
      key: 'fileName',
      width: '50%',
      render: (fileName: string) => {
        const arr = fileName.split(/:(.*)/, 2);

        return (
          <div className="flex w-full items-center">
            <SvgIcon color="#33ADFF" icon="icon-api" size={24} />
            <Text
              ellipsis={{ tooltip: arr[1] }}
              className="ml-2"
              style={{ maxWidth: isPc ? `${parentSize.width * 0.5}px` : '100px' }}
            >
              {arr[1]}
            </Text>
          </div>
        );
      },
    },
    {
      title: '请求方法',
      dataIndex: 'fileName',
      key: 'method',
      render: (fileName: string) => {
        const arr = fileName.split(/:(.*)/, 2);

        return (
          <div className="min-w-14 max-w-14 rounded-[4px] border border-line-2 bg-bg-4 px-2 text-center">
            <span>{arr[0].toUpperCase()}</span>
          </div>
        );
      },
    },
    {
      title: '时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: '200px',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
      onCell: () => ({ style: { flex: '1' } }),
    },
    {
      title: '操作',
      key: 'action',
      width: '100px',
      render: (_, record: Collection) => (
        <div className="flex items-center">
          {isAdmin ? (
            <Dropdown
              menu={{
                items: [
                  {
                    key: '2',
                    label: '删除此数据接口',
                    onClick: () => {
                      setEditItem(record);
                      setDeleteModalVisible(true);
                    },
                  },
                  {
                    key: '3',
                    label: '编辑接口参数',
                    onClick: () => {
                      setEditItem(record);

                      fetchExpandedData(record);
                      setApiEditModalVisible(true);
                    },
                  },
                ],
              }}
              trigger={isPc ? ['hover'] : ['click']}
              placement="bottomLeft"
            >
              <Button
                type="text"
                icon={<EllipsisOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              >
                更多
              </Button>
            </Dropdown>
          ) : (
            '-'
          )}
        </div>
      ),
      // onCell: () => ({ style: { width: '300px' } }),
    },
  ];

  const handlePageChange = (page: number, pageSize: number) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const paginationConfig = {
    current: page,
    pageSize: pageSize,
    pageSizeOptions: [10, 20, 50, 100],
    total: total,
    onChange: handlePageChange,
    showQuickJumper: true,
    showSizeChanger: true,
  };

  const { run } = useDebounceFn(
    async () => {
      await getCollections();
    },
    {
      wait: 300,
    },
  );

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const getCollections = async () => {
    try {
      if (!selectedItem) {
        return;
      }
      const res = await datasetService.getDatasetFileList({
        datasetId: selectedItem?._id || selectedItem?.id || '',
        page: page,
        page_size: pageSize,
        searchText: searchValue,
        offset: (page - 1) * pageSize,
        app_id: appId, //必填
        type: 'API',
      });
      setCollections(res.list);
      setTotal(res.total);
    } catch (error) {
      console.error(error);
    } finally {
      clearSelections();
      setLoading(false);
    }
  };

  const rename = async () => {
    const newPath = path.trim();
    const fullName = `${method}:${newPath}`;
    if (!newPath) {
      message.error('名称不能为空');
      return;
    }
    if (newPath.length > MAX_NAME_LENGTH) {
      message.error(`名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!editItem) {
      return;
    }
    await datasetService.updateDatasetCollection({
      id: editItem?._id,
      name: fullName,
    });
    message.success('修改名称成功！');
    setRenameModalVisible(false);
    setEditItem(undefined);
    run();
  };

  const handleDeleteConfirm = async () => {
    if (isBatchDelete) {
      const promises = selectedRows.map(async (row) => {
        await datasetService.datasetDeleteApi({
          collectionId_list: [row?.collectionId],
          appId: appId, //必填
          datasetId: selectedRows[0]?.datasetId,
        });
      });

      await Promise.all(promises);
    } else {
      if (!editItem) {
        return;
      }
      await datasetService.datasetDeleteApi({
        collectionId_list: [editItem?.collectionId],
        appId: appId, //必填
        datasetId: editItem?.datasetId,
      });
    }
    message.success('删除成功！');
    setDeleteModalVisible(false);
    setEditItem(undefined);
    setIsBatchDelete(false);
    clearSelections();
    run();
  };

  const handleBatchDelete = async () => {
    setIsBatchDelete(true);
    setDeleteModalVisible(true);
  };

  useEffect(() => {
    setPage(1);
    setPageSize(10);
    setTotal(0);
    if (selectedItem) {
      setLoading(true);
      run();
    } else {
      run();
      setCollections([]);
    }
  }, [selectedItem]);

  useUpdateEffect(() => {
    setLoading(true);
    run();
  }, [page, pageSize]);

  useUpdateEffect(() => {
    setLoading(true);
    setPage(1);
    setPageSize(10);
    run();
  }, [searchValue]);



  event$?.useSubscription((val) => {
    if (val == ApiDatasetEvent.REFRESHCOLLECTION) {
      setLoading(true);
      setPage(1);
      setPageSize(10);
      setTotal(0);
      setSearchValue('');
      run();
    }
  });

  return (
    <div className="relative flex h-full flex-col gap-4 overflow-y-auto">
      <div className="left-0 top-2 z-10 w-[200px]">
        {isPc && (
          <Input
            style={{ border: '1px solid #E5E6EB', color: '#C9CEE2' }}
            placeholder="搜索"
            value={searchValue}
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            onChange={(e) => {
              setSearchValue(e.target.value);
            }}
          />
        )}
      </div>

      <Tables
        rowClassName="bg-[#fff] custom-scrollbar"
        className="custom-scrollbar"
        loading={loading}
        dataSource={collections}
        columns={columns}
        paginationProps={paginationConfig}
        rowSelection={isAdmin ? rowSelection : {}}
        rowKey={'_id'}
        expandable={{
          expandedRowRender: (record) => (
            <div>
              {expandLoading[record._id] ? (
                <Spin />
              ) : (
                <Descriptions
                  size="small"
                  column={1}
                  contentStyle={{ fontSize: '12px', color: '#a3a3a3' }}
                  labelStyle={{ fontSize: '12px' }}
                >
                  <Descriptions.Item label="数据接口名称">
                    {expandedData[record._id]?.function.name}
                  </Descriptions.Item>
                  <Descriptions.Item label="数据接口说明">
                    <div style={{ maxWidth: `${parentSize.width * 0.8}px` }}>
                      {expandedData[record._id]?.function.description}
                    </div>
                  </Descriptions.Item>
                  <Descriptions.Item>
                    <div style={{ maxWidth: `${parentSize.width * 0.8}px` }}>
                      {parameterList(expandedData[record._id])}
                      {/* {parameterList(record)} */}
                    </div>
                  </Descriptions.Item>
                </Descriptions>
              )}
            </div>
          ),
          rowExpandable: (record) => record.name !== 'Not Expandable',
          onExpand: (expanded, record) => {
            if (expanded && !expandedData[record._id]) {
              fetchExpandedData(record);
            }
          },
          columnWidth: 10,
        }}
        locale={{
          emptyText: (
            <div className="h-full" style={{ textAlign: 'center', color: '#999' }}>
              {!loading && <EmptyTip />}
            </div>
          ),
        }}
      ></Tables>

      {selectedRows.length > 0 && isAdmin && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            ></Button>
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            <Button style={{ color: '#fff' }} type="text" onClick={handleBatchDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <Modals
        title={<div style={{ textAlign: 'center', width: '100%' }}>重命名</div>}
        open={renameModalVisible}
        onCancel={() => {
          setRenameModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        width={300}
        centered
        onOk={rename}
      // footer={
      //   <div style={{ textAlign: 'center' }}>
      //     <Space size={56}>
      //       <Button
      //         onClick={() => {
      //           setRenameModalVisible(false);
      //         }}
      //       >
      //         取消
      //       </Button>
      //       <Button type="primary" onClick={rename}>
      //         确定
      //       </Button>
      //     </Space>
      //   </div>
      // }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={path} onChange={(e) => setPath(e.target.value)} />
        </div>
      </Modals>

      <DeleteConfirmModal
        visible={deleteModalVisible}
        text={`确定要删除吗？`}
        onCancel={() => {
          setDeleteModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
      />

      <ApiEditModal
        visible={apiEditModalVisible}
        onCancel={() => {
          console.log('取消');
          setApiEditModalVisible(false);
        }}
        onConfirm={submit}
        onItem={onItem}
        title={'编辑'}
        isErr={'true'}
      />
    </div>
  );
};

export default ApiTable;
